package cn.micro.system.manage.service.impl;

import cn.micro.system.manage.common.constants.SystemConstants;
import cn.micro.system.manage.entity.SysDimDept;
import cn.micro.system.manage.entity.SysDimDeptRole;
import cn.micro.system.manage.entity.SysDimPosition;
import cn.micro.system.manage.mapper.SysDimDeptMapper;
import cn.micro.system.manage.mapper.SysDimDeptRoleMapper;
import cn.micro.system.manage.mapper.SysDimPositionMapper;
import cn.micro.system.manage.service.SysDimDeptRoleService;
import cn.micro.system.manage.service.SysDimDeptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织机构 服务实现类
 * </p>
 *
 * @author wr
 * @since 2023-12-25
 */
@Service
@RequiredArgsConstructor
public class SysDimDeptServiceImpl extends ServiceImpl<SysDimDeptMapper, SysDimDept> implements SysDimDeptService {

    private final SysDimPositionMapper sysDimPositionMapper;

    private final SysDimDeptRoleService sysDimDeptRoleService;

    @Override
    public List<SysDimDept> getByName(SysDimDept sysDimDept) {
        LambdaQueryWrapper<SysDimDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(sysDimDept.getName()),SysDimDept::getName, sysDimDept.getName())
                .ne(StringUtils.isNotEmpty(sysDimDept.getId()),SysDimDept::getId, sysDimDept.getId());
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        LambdaQueryWrapper<SysDimPosition> positionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        positionLambdaQueryWrapper.eq(SysDimPosition::getDeptId,id);
        sysDimPositionMapper.delete(positionLambdaQueryWrapper);
        LambdaQueryWrapper<SysDimDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDimDept::getId,id)
                .or()
                .apply("CONCAT (',',tree_path,',') LIKE CONCAT('%,',{0},',%')", id);
        this.remove(queryWrapper);
        //删除相关的角色关联信息
        sysDimDeptRoleService.remove(new LambdaQueryWrapper<SysDimDeptRole>().eq(SysDimDeptRole::getDeptId,id));
    }

    @Override
    @Transactional
    public boolean saveDept(SysDimDept sysDimDept) {
        sysDimDept.setTreePath(generateMenuTreePath(sysDimDept.getParentId()));
        boolean save = this.save(sysDimDept);
        if (save && sysDimDept.getRoleIds() != null && sysDimDept.getRoleIds().size() > 0){
            List<SysDimDeptRole> deptRoleList = new ArrayList<>();
            for (String roleId : sysDimDept.getRoleIds()){
                SysDimDeptRole deptRole = new SysDimDeptRole();
                deptRole.setRoleId(Long.parseLong(roleId));
                deptRole.setDeptId(Long.parseLong(sysDimDept.getId()));
                deptRoleList.add(deptRole);
            }
            save = sysDimDeptRoleService.saveBatch(deptRoleList);
        }
        return save;
    }


    /**
     * 部门路径生成
     *
     * @param parentId 父ID
     * @return 父节点路径以英文逗号(, )分割，eg: 1,2,3
     */
    private String generateMenuTreePath(Long parentId) {
        String treePath = null;
        if (SystemConstants.MENU_ROOT_NODE.equals(parentId)) {
            treePath = String.valueOf(parentId);
        } else {
            SysDimDept parent = this.getById(parentId);
            if (parent != null) {
                treePath = parent.getTreePath() + "," + parent.getId();
            }
        }
        return treePath;
    }
}
